local jinti = fk.CreateSkill{
  name = "xiaobai__jinti",
  dynamic_desc = function (self, player)
    local xiangshu = player:getMark("xiaobai__jinti")
    local result = "xiaobai__jinti_inner:"
    local list = {}
    for i = 1,xiangshu-1,1 do
      table.insert(list,"#jinti-use")
    end
      table.insert(list,"#jinti-draw")
    for i = xiangshu+1,5,1 do
      table.insert(list,"#jinti-use")
    end
    return result..table.concat(list,":")
  end,
}

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["xiaobai__jinti"] = "进替",
  [":xiaobai__jinti"] = "出牌阶段限一次，你可以依次：摸牌至四张，使用一张牌，"..
    "使用一张牌，使用一张牌，使用一张牌。因此使用的牌于“摸牌至四张”前不受次数限制，之后需为本回合未被使用过的花色的牌。然后你交换“摸牌至四张”和最后执行的项。",
  [":xiaobai__jinti_inner"] = "出牌阶段限一次，你可以依次：{1}，{2}，"..
    "{3}，{4}，{5}。因此使用的牌于“摸牌至四张”前不受次数限制，之后需为本回合未被使用过的花色的牌。然后你交换“摸牌至四张”和最后执行的项。",
  ["@xiaobai__jinti_suit-turn"] = "进替",
  ["#jinti-start"] = "进替：你可以依次执行：",
  ["#jinti-use"] = "使用一张牌",
  ["#jinti-draw"] = "将手牌摸至四张",
  ["#jinti-choose2Use"] = "进替：你可以使用一张牌（不能用已使用过的花色）",
  ["#jinti-choose2Use_extraUse"] = "进替：你可以使用一张牌（不受次数限制）",
  ["#jinti-choose2draw4"] = "进替：你可以摸牌至4张（若已有至少四张牌则跳过此项）",
}

jinti:addEffect("active",{
  anim_type = "offensive",
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and (player:getMark("xiaobai__jinti") == 1 or
    table.find(player:getHandlyIds(true), function(id)
      local card = Fk:getCardById(id)
      return player:canUse(card, {bypass_times = true}) and not player:prohibitUse(card)
    end))
  end,
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  target_filter = Util.FalseFunc,
  prompt = function (self, player, selected_cards, selected_targets)
    if player == nil then
      return ""
    end
    local xiangshu = player:getMark("xiaobai__jinti")
    local result = Fk:translate("#jinti-start")
    for i = 1, xiangshu-1, 1 do
      result = result + ' ' + i + "." +Fk:translate("#jinti-use")
    end
    result = result + ' ' + xiangshu + "." + Fk:translate("#jinti-draw")
    for i = xiangshu+1, 5, 1 do
      result = result + ' ' + i + "." +Fk:translate("#jinti-use")
    end
    return result
  end,
  on_use = function (self, room, effect)
    local player = effect.from
    local jinti_order = player:getMark("xiaobai__jinti")
    if jinti_order < 0 then
      jinti_order = 0
    end
    room:setPlayerMark(player, "xiaobai__jinti", 0)
    for i = 1, 5, 1 do
      if i == jinti_order then
        if player:getHandcardNum() < 4 then
          if not (room:askToSkillInvoke(player, {skill_name = self.name, prompt = "#jinti-choose2draw4"})) then
            break
          end 
        end
        local draw_num = 4 - player:getHandcardNum()
        if draw_num > 0 then
          player:drawCards(draw_num, self.name)
        end
        room:addPlayerMark(player, "xiaobai__jinti", 1)
      elseif i < jinti_order then
          local use = room:askToPlayCard(player, {
            pattern = ".",
            skill_name = self.name,
            prompt = "#jinti-choose2Use_extraUse",
            extra_data = {
              extraUse = true,
              bypass_times = true},
            })
          if not use then
            break
          else
            room:addPlayerMark(player, "xiaobai__jinti", 1)
          end
      else
        local suits_mark = player:getMark("@xiaobai__jinti_suit-turn")
        local suits = {}
        if type(suits_mark) == "table" then 
          suits = table.map(suits_mark, function (element, index, array)
            return U.ConvertSuit(element, "sym", "str")
          end)
        end
        local patterns = ".|.|^("..table.concat(suits, ',') ..")"
        local use = room:askToPlayCard(player, {
          pattern = patterns,
          skill_name = self.name,
          prompt = "#jinti-choose2Use"})
        if not use then
          break
        else
          room:addPlayerMark(player, "xiaobai__jinti", 1)
        end
      end
    end
    if player:getMark("xiaobai__jinti") == 0 then
      room:setPlayerMark(player,"xiaobai__jinti",jinti_order)
    end
  end
})

jinti:addEffect(fk.CardUseFinished,{
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self) and player:hasSkill(jinti.name)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local suit = data.card:getSuitString(true)
    local ids = player:getTableMark("@xiaobai__jinti_suit-turn") or {}
    if suit == "log_nosuit" then
      return
    end
    table.insertIfNeed(ids, suit)
    room:setPlayerMark(player, "@xiaobai__jinti_suit-turn", ids)
  end
})

jinti:addAcquireEffect(function (self, player, is_start)
  local ids = {}
  local room = player.room
  room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
    local use = e.data
    if use.from ~= player then return false end
    local record = use.card:getSuitString(true)
    if record ~= "log_nosuit" then
      table.insertIfNeed(ids, record)
    end
  end, Player.HistoryTurn)
  if #ids > 0 then
    room:setPlayerMark(player, "@xiaobai__jinti_suit-turn", ids)
  end
  player.room:setPlayerMark(player,"xiaobai__jinti",1)
end)

return jinti